package com.kkd.kkdapp.activity;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import pl.droidsonroids.gif.GifDrawable;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.google.gson.Gson;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.MyDiscountCouponAdapter;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.http.entity.AccountInfoRes;
import com.kkd.kkdapp.http.entity.AllConfig;
import com.kkd.kkdapp.http.entity.BankCard;
import com.kkd.kkdapp.http.entity.Home;
import com.kkd.kkdapp.http.entity.HomeData;
import com.kkd.kkdapp.http.entity.MyDiscountCouponData;
import com.kkd.kkdapp.http.entity.MyDiscountCouponDataList;
import com.kkd.kkdapp.http.entity.WithDrawRes;
import com.kkd.kkdapp.http.entity.WithdrawTipsData;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.AppUtil.onToastDismiss;
import com.kkd.kkdapp.view.EditText.FinanceEditText;
import com.kkd.kkdapp.view.EditText.FinanceEditText.onFinanceEditListener;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 提现
 * 
 * @author mty
 * 
 *         * @refactor 赵闯 2016-5-17
 */
public class WithdrawActivity extends BaseActivity implements OnClickListener {
	// private String version; // 当前App版本号
	private static final int WITHDRAW_SUCCESS = 1; // 提现成功
	private static final int WITHDRAW_FAIL = 2; // 提现失败
	private static final int DECIMAL_DIGITS = 3; // 输入框小数的位数
	private static final int NO_BANK_CARD = 4; // 输入框小数的位数
	private static final int GOT_ACCOUNT_INFO = 5; // 获取账户信息成功
	private static final int GOT_COUPON = 7; // 优惠券获取成功
	private static final int FAIL_TOAST = 9; // 请求失败，显示返回的提示

	private RelativeLayout mBackBtn; // 返回
	private TextView mBalanceTv; // 可提现余额
	private FinanceEditText mCashCountEt; // 取现金额
	private EditText mPswEt; // 取现密码
	private Button mWithdrawBtn; // 提现
	private RelativeLayout withdraw_rl;
	private Button next_bt;
	private TextView mAstrictTv; // 提现约束
	private TextView will_get_tv;
	private TextView mForgetPswTv; // 忘记密码
	private TextView mAstrictByDayTv; // 提现每日限制
	private ImageView mCardImg; // 银行图标
	private TextView mCardNumberTv; // 卡号
	private TextView mBankNameTv; // 银行名字
	private TextView astrict_bank;
	// private TextView mReminderTv; // 提现手续费提示
	// private TextView mReminderTailTv;// 提现手续费提示尾部的金额
	private TextView mCouponTv; // 优惠券描述
	private TextView mAmountTv; // 优惠券额度
	private RelativeLayout mSelectRl; // 选择优惠券
	private TextView details;
	private TextView user_fee;
	private TextView withdraw_time;
	private ImageView progressbar;
	private RelativeLayout pop_line;
	private RelativeLayout mReminderRl; // 提现手续费 动画布局
	private ImageView close;
	private TextView withdraw_count_tv;
	private String newMisTips; // 是否显示新手任务
	private long timeSpace; // 是否显示新手任务
	private Dialog mDialog;

	private double mMyBalance; // 账户余额
	private String[] bankStatusas;
	private String bmouts; // 账户余额 字符串
	private String bmout; // 账户可提现余额 字符串
	private double mSingleMax; // 单笔取现最大限额
	private BankCard mBankCard;
	private List<MyDiscountCouponDataList> mDataList; // 可用优惠券链表
	MyDiscountCouponDataList mCurCoupon; // 当前使用的优惠券
	private String Title; // 优惠券标题
	private double mAmount = 0; // 优惠券面值 ，分为单位
	private double mUserWant = 0; // 用户要提现的金额
	// private boolean isWantMax = false; // 用户是否想要提取最大限额
	private String mCouponId = ""; // 优惠券id
	private double mWithDrawFee;
	private DecimalFormat df = new DecimalFormat("0.00");
	private WithDrawRes mWithDrawRes;
	private String cardNo;
	private String bankName;
	private String[] everymax;
	private String imageUrl;
	private AllConfig mAllConfig;
	public int mId = MyDiscountCouponAdapter.NOT_UESE;// 当前选择的优惠券id
	private WithdrawTipsData withdrawTips;// 提现页面是否开启特权
	private AccountInfoRes mAccountInfo;
	private HomeData mHomeData;
	private String jumpTo;
	private Dialog mSinaDialog;
	private Dialog loadDialog;
	private boolean isRequestCouponList = true;// 只请求一次优惠券接口
	private int statusCode;

	// private Dialog loadDialog;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			// if (loadDialog != null) {
			// loadDialog.dismiss();
			// }
			switch (msg.what) {
			case WITHDRAW_SUCCESS:
				withDrawing = false;
				close.setClickable(true);
				updateWithdrawBtn();
				if (!TextUtils.isEmpty(mWithDrawRes.getResponseContent())) {
					Intent intent = new Intent(WithdrawActivity.this,
							KKDSinaWebActivity.class);
					intent.putExtra("url", "");
					intent.putExtra("data", mWithDrawRes.getResponseContent());
					intent.putExtra("useTitleName", true);
					intent.putExtra("titleName", "新浪支付");
					startActivity(intent);
				} else {
					details.setText("预计到账时间为："
							+ mWithDrawRes.getExpectedArrivalDate());
					progressbar.setImageResource(R.drawable.recharge_suc);
					showToast("提现成功");
				}

				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						finish();
					}
				}, 1000);
				// showDialog("预计到账时间为：" + expectedArrivalDate, true);
				break;
			case GOT_ACCOUNT_INFO:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				if (mAccountInfo.getWithholdAuth().getWithdrawStatus() == 1) {

					showSinaDialog();
				} else {
					if (PreferenceUtils.getInstance().getWithdrawPassWord(
							WithdrawActivity.this) != 1) {
						requestIsSetPayPassword();
					}
				}
				// mReminderTv.setText("可提现余额=账户余额 （" + bmouts +
				// "元）- 提现手续费（2元）");
				mBalanceTv.setText(bmouts);
				mCardNumberTv.setText(cardNo);
				mBankNameTv.setText(bankName);
				astrict_bank.setText(bankName + "提现限额");
				mAstrictTv.setText(everymax[0]);
				mAstrictByDayTv.setText(everymax[1] + "元");
				ImageLoader.getInstance().displayImage(imageUrl, mCardImg);
				if (mBankCard != null) {
					bankStatusas = mBankCard.getBankStatus().split(",");

				}

				break;
			case GOT_COUPON:
				if (mDataList != null && mDataList.size() > 0) {
					onGotCoupon();
				} else {
					mCouponTv.setText(R.string.coupon_null);
					mAmountTv.setVisibility(View.GONE);
					if (withdrawTips != null) {
						if (!TextUtils.isEmpty(withdrawTips.getTips1())
								&& !TextUtils.isEmpty(withdrawTips.getTips1())) {
							tv_toOpenTequan.setText(withdrawTips.getTips1()
									+ "\n" + withdrawTips.getTips2());
							tv_toOpenTequan.setVisibility(View.VISIBLE);
						} else {
							tv_toOpenTequan.setVisibility(View.GONE);
						}
					} else {
						tv_toOpenTequan.setVisibility(View.GONE);
					}

				}
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				break;
			case FAIL_TOAST:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				String couponDesc = (String) msg.obj;
				if (statusCode == KkdHttpClient.NO_NET) {
					showToast("网络错误，请稍后重试", new onToastDismiss() {

						@Override
						public void onToastDismiss() {
							finish();
						}
					});
				} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
					showToast("服务异常，请稍后重试", new onToastDismiss() {

						@Override
						public void onToastDismiss() {
							finish();
						}
					});
				}

				break;
			case WITHDRAW_FAIL:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				withDrawing = false;
				close.setClickable(true);
				details.setText((String) msg.obj);
				progressbar.setImageResource(R.drawable.recharge_failture);
				if (mAccountInfo.getWithholdAuth().getWithdrawStatus() == 1) {
					if (statusCode == KkdHttpClient.NO_NET) {
						showToast("网络错误，请稍后重试");
					} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
						showToast("服务异常，请稍后重试");
					}else{
						showToast((String) msg.obj);
					}
				}else{
					showToast((String) msg.obj);
				}
				break;
			case NO_BANK_CARD:
				Intent intent = new Intent(WithdrawActivity.this,
						ForTenderActivity.class);
				intent.putExtra("enterTypeFlag", 2);
				startActivity(intent);
				break;
			default:
				break;
			}
		};
	};
	private TextView tv_toOpenTequan;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_withdraw);
		initUI();
		// couponList();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getAccountInfo();
	}

	@Override
	protected void onDestroy() {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		super.onDestroy();
	}

	protected void onGotCoupon() {
		mId = 0;
		mCurCoupon = mDataList.get(0);
		mCouponId = mCurCoupon.getCouponId();
		mAmount = (mCurCoupon.getAmount() * 0.01) > mWithDrawFee ? mWithDrawFee
				: mCurCoupon.getAmount() * 0.01;
		mCouponTv.setText(mCurCoupon.getTitle());
		mAmountTv.setText("¥" + df.format(mAmount));
		if ((mMyBalance - mWithDrawFee + mAmount) > 0) {
			bmout = df.format(mMyBalance - mWithDrawFee + mAmount);
		} else {
			bmout = df.format(0.00);
		}
		// mBalanceTv.setText(bmout);
		// updateReminderTv();

	}

	/**
	 * 初始化组件
	 */
	public void initUI() {
		tv_toOpenTequan = (TextView) findViewById(R.id.tv_toOpenTequan);
		mBackBtn = (RelativeLayout) this.findViewById(R.id.withdraw_title_img);
		mBackBtn.setOnClickListener(this);
		mWithdrawBtn = (Button) this.findViewById(R.id.withdraw_bt);
		will_get_tv = (TextView) findViewById(R.id.will_get_tv);
		next_bt = (Button) this.findViewById(R.id.next_bt);
		close = (ImageView) findViewById(R.id.close);
		close.setOnClickListener(this);
		astrict_bank = (TextView) findViewById(R.id.astrict_bank);
		details = (TextView) findViewById(R.id.details);
		progressbar = (ImageView) findViewById(R.id.progressbar);
		withdraw_rl = (RelativeLayout) findViewById(R.id.withdraw_rl);
		user_fee = (TextView) findViewById(R.id.user_fee);
		withdraw_time = (TextView) findViewById(R.id.withdraw_time);
		mAllConfig = PreferenceUtils.getInstance().getAllConfigData(this);
		if (mAllConfig != null && mAllConfig.getHomeData() != null) {
			if (!TextUtils.isEmpty(mAllConfig.getHomeData().getUserFee())) {
				user_fee.setText(mAllConfig.getHomeData().getUserFee());
			}
			if (!TextUtils.isEmpty(mAllConfig.getHomeData().getWithdrawTime())) {
				withdraw_time.setText(mAllConfig.getHomeData()
						.getWithdrawTime());
			}
		}
		next_bt.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				// withdraw();
				nextAction();

			}
		});
		mWithdrawBtn.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				// TODO 提现
				actionWithdraw();

			}
		});

		mSelectRl = (RelativeLayout) this.findViewById(R.id.discount);
		pop_line = (RelativeLayout) this.findViewById(R.id.pop_line);
		mSelectRl.setOnClickListener(this);
		mForgetPswTv = (TextView) this.findViewById(R.id.forget_ps);
		mForgetPswTv.setOnClickListener(this);
		withdraw_count_tv = (TextView) findViewById(R.id.withdraw_count_tv);
		mBalanceTv = (TextView) this.findViewById(R.id.withdraw_balance);
		mCashCountEt = (FinanceEditText) this.findViewById(R.id.withdraw_money);
		mPswEt = (EditText) this.findViewById(R.id.withdraw);
		mCardNumberTv = (TextView) this.findViewById(R.id.card_number);
		mAstrictTv = (TextView) this.findViewById(R.id.astrict);

		mAstrictByDayTv = (TextView) this.findViewById(R.id.everyday_tv);
		mCardImg = (ImageView) this.findViewById(R.id.card_img);
		mBankNameTv = (TextView) this.findViewById(R.id.card_name);
		// mReminderTv = (TextView) this.findViewById(R.id.reminder_tv);
		mReminderRl = (RelativeLayout) this.findViewById(R.id.reminder_rl);

		mCouponTv = (TextView) this.findViewById(R.id.discount_tv);
		mAmountTv = (TextView) this.findViewById(R.id.discount_unused);
		// mReminderTailTv = (TextView) this.findViewById(R.id.reminder_tv1);

		mCashCountEt.setFinanceEditListener(new onFinanceEditListener() {

			@Override
			public void onValueChanged(double toValue, double fromValue) {
				withdrawMoneyLogic(); // 校验提现金额的合法性
			}

			@Override
			public void onOutLimit() {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterValueChanged(double toValue) {
				updateWithdrawBtn();
			}
		});
		mCashCountEt.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT) {
					if (next_bt.isEnabled())
						nextAction();
				}
				return false;
			}
		});

		mPswEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				boolean enable = false;
				if (!TextUtils.isEmpty(s.toString())) {
					enable = true;
				}

				mWithdrawBtn.setEnabled(enable);
				// if(s.toString().length()==6)
				// withdraw();
			}
		});
		mPswEt.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					if (mWithdrawBtn.isEnabled())
						actionWithdraw();
				}
				return false;
			}
		});

	}

	protected void actionWithdraw() {
		SystemUtils.onEvent("Account_WithDraw_Submit", 1);
		SystemUtils.hideKeyBoard(WithdrawActivity.this);
		withdraw_rl.setVisibility(View.GONE);
		mWithdrawBtn.setVisibility(View.GONE);
		details.setVisibility(View.VISIBLE);
		details.setText("正在校验...");
		close.setClickable(false);
		progressbar.setVisibility(View.VISIBLE);
		GifDrawable drawable;
		try {
			drawable = new GifDrawable(getResources(), R.drawable.loading_gif);

			progressbar.setImageDrawable(drawable);
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		withdraw();
	}

	protected void nextAction() {
		if (mAccountInfo.getWithholdAuth().getWithdrawStatus() == 1) {
			if (mAccountInfo.getWithholdAuth().getIsWithholdAuth() == 0) {
				showSinaDialog();
			} else {
				withdraw();
			}
		} else {
			if (bankStatusas[1].equals("1")) {
				withdraw_rl.setVisibility(View.VISIBLE);
				mWithdrawBtn.setVisibility(View.VISIBLE);
				details.setVisibility(View.GONE);
				progressbar.setVisibility(View.GONE);
				pop_line.setVisibility(View.VISIBLE);
				String count = mCashCountEt.getText().toString();
				if (count.endsWith("."))
					count = count.substring(0, count.length() - 1);
				withdraw_count_tv.setText(count);
				mPswEt.requestFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(mPswEt, InputMethodManager.SHOW_IMPLICIT);
			} else if (bankStatusas[1].equals("0")) {

				showDialog("由于新浪支付业务调整，暂停此银行提现服务。请使用其他银行储蓄卡进行交易", false);
			}
		}
	}

	/**
	 * 提现金额输入 合法性校验
	 */
	protected void inputCheckout() {
		String inputmoney = mCashCountEt.getText().toString();
		String dValue = inputmoney.toString();
		String[] splitArray = dValue.split("\\.");
		String newValue;
		if (decimals(inputmoney)) { // 输入金额为整数、两位小数
			if (".".equals(inputmoney.toString())) { // 输入提现金额首位为“.”
				mCashCountEt.setText("0.");
				mCashCountEt.setSelection(mCashCountEt.getText().toString()
						.length());
			} else {
				// 去掉合法输入的首位的0
				boolean isReset = false;
				while (splitArray[0].startsWith("0")
						&& splitArray[0].length() > 1) {
					splitArray[0] = splitArray[0].substring(1);
					isReset = true;
				}
				if (splitArray.length > 1) {
					newValue = splitArray[0] + "." + splitArray[1];
				} else {
					newValue = splitArray[0];
				}
				if (isReset) {
					mCashCountEt.setText(newValue);
				}

			}

		} else { // 输入金额不为整数、两位小数

			if (TextUtils.isEmpty(splitArray[0])) {
				splitArray[0] = "0";
			} else {
				// 去掉合法输入的首位的0
				double first2 = Double.parseDouble(splitArray[0]);
				splitArray[0] = String.valueOf(((int) first2));
			}
			if (splitArray.length > 1) {
				newValue = splitArray[0] + "." + splitArray[1];
			} else {
				newValue = splitArray[0] + ".";
			}

			String[] splitArray2 = newValue.split("\\.");
			if (splitArray2.length > 1) {
				String dotValue = splitArray2[1];
				int diff = dotValue.length() - DECIMAL_DIGITS;
				if (diff < 0)
					diff = 0;
				newValue = newValue.substring(0, splitArray2[0].length()
						+ splitArray2[1].length() + 1 - diff);
			}
			mCashCountEt.setText(newValue);
			mCashCountEt.setSelection(mCashCountEt.getText().toString()
					.length());
		}

	}

	/**
	 * 提现金额输入框逻辑
	 */
	public void withdrawMoneyLogic() {

		String inputmoney = "";
		if (mId == MyDiscountCouponAdapter.NOT_UESE) {
			mAmount = 0;
		} else {
			if (mCurCoupon != null) {
				mAmount = (mCurCoupon.getAmount() * 0.01) > mWithDrawFee ? mWithDrawFee
						: mCurCoupon.getAmount() * 0.01;
			}
		}

		if (mCashCountEt.getText() != null) {
			inputmoney = mCashCountEt.getText().toString();
		}
		if (TextUtils.isEmpty(inputmoney)) {
			mUserWant = 0.0f;
			will_get_tv.setTextColor(0xffa8a8a8);
			will_get_tv.setText("实际到账:0.00元");
		} else {
			if (inputmoney.startsWith(".")) { // 首位为“.” ,则补成“0.XX”
				inputmoney = "0" + inputmoney;
			}
			if (inputmoney.substring(inputmoney.length() - 1).equals(".")) {
				inputmoney = inputmoney.substring(0, inputmoney.length() - 1); // 去掉末尾的小数点
			}

			mUserWant = Double.parseDouble(inputmoney);
			double nBmout = getBmoutFormat();// 获取当前可提余额最大值 ,保证不为负，并保留2位小数
			double limit = (mMyBalance > mSingleMax ? mSingleMax : mMyBalance);
			df.format(limit);
			if (mUserWant > limit) {
				// mUserWant = limit;
				// mCashCountEt.setText(df.format(mUserWant));
				// mCashCountEt.setSelection(mCashCountEt.getText().toString()
				// .length());
				if (mUserWant > mSingleMax) {
					// String tip = "该银行卡快捷支付单笔交易限额" + everymax[0] +
					// "元，大额交易请使用网银";
					// showDialog(tip, false);
					will_get_tv.setTextColor(0xffff0000);
					if (everymax != null)
						will_get_tv.setText("该银行卡快捷支付单笔交易限额" + everymax[0]
								+ "元，大额交易请使用网银");
				} else {
					will_get_tv.setTextColor(0xffff0000);
					will_get_tv.setText("输入金额不得大于账户余额");
					// String tip = "您可提现金额为" + df.format(mMyBalance) + "元";
					// if (nBmout != 0) {
					// tip = "提现需扣除" + df.format(2 - mAmount) + "元手续费，您最多可提取"
					// + df.format(nBmout) + "元";
					// } else {
					// tip = "您可提现金额为" + df.format(nBmout) + "元，不能提现";
					// }
					// showDialog(tip, mMyBalance == 0);
				}
			} else {
				will_get_tv.setTextColor(0xffa8a8a8);
				will_get_tv
						.setText("实际到账:"
								+ df.format((mUserWant - mWithDrawFee + mAmount) > 0 ? (mUserWant
										- mWithDrawFee + mAmount)
										: 0) + "元");
				updateWithdrawBtn();
			}

			// isWantMax = isUserWantMax(); // 更新用户是否想提取最大限额
		}
	}

	/*********************
	 * 获取当前可提余额最大值 ,保证不为负，并保留2位小数
	 ****************/
	private double getBmoutFormat() {
		double nBmout = (mMyBalance - mWithDrawFee + mAmount) > 0 ? (mMyBalance
				- mWithDrawFee + mAmount) : 0;
		// double nBmout = (mMyBalance + mAmount) > 0 ? (mMyBalance + mAmount)
		// : 0;
		nBmout = Double.parseDouble(df.format(nBmout));
		return nBmout;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.withdraw_title_img: // 返回
			finish();
			break;
		case R.id.forget_ps: // 忘记密码
			Intent intent = new Intent(this, WithdrawUpdateActivity.class);
			startActivity(intent);
			break;
		case R.id.discount: // 选择优惠券
			if (mDataList != null && mDataList.size() > 0) {

				intent = new Intent(this, WithdrawDiscountCounponActivity.class);
				intent.putExtra("mId", mId);
				intent.putExtra("mCouponId", mCouponId);
				startActivityForResult(intent, 60);

			} else {
				if (withdrawTips != null) {
					if (!TextUtils.isEmpty(withdrawTips.getTips1())
							&& !TextUtils.isEmpty(withdrawTips.getTips1())) {
						if (withdrawTips.getTips1().contains("新手")) {
							intent = new Intent(WithdrawActivity.this,
									KKDWebActivity.class);
							try {
								Gson gson = new Gson();

								String cache = PreferenceUtils.getInstance()
										.getHomeData(this);
								if (!TextUtils.isEmpty(cache)) {

									Home home = gson
											.fromJson(cache, Home.class);
									mHomeData = home.getData();
									if (mHomeData != null) {
										jumpTo = mHomeData.getQuickIn().get(0)
												.getJumpTo();
									}
								}
							} catch (Exception e) {
								// 忽略
							}
							if (!TextUtils.isEmpty(jumpTo)) {
								intent.putExtra("url", jumpTo);
							}
						} else {
							intent = new Intent(WithdrawActivity.this,
									HomeActivity.class);
							HomeActivity.mActivity.homeNavigation();
						}
						finish();
						startActivity(intent);
					}
				}
			}
			break;
		case R.id.close:
			closePopwin();

			break;
		}

	}

	/**
	 * closePopwin:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 */
	private void closePopwin() {
		// TODO Auto-generated method stub
		if (pop_line.getVisibility() == View.VISIBLE) {
			pop_line.setVisibility(View.GONE);
		}
		mCouponId = "";
		mAmount = 0;
		mPswEt.setText("");
		mCashCountEt.setText("");
		will_get_tv.setText("实际到账:0.00元");
		getAccountInfo();
	}

	private boolean withDrawing = false;

	/**
	 * 提现接口
	 */

	public void withdraw() {
		if (!withDrawing) {
			if (mAccountInfo.getWithholdAuth().getWithdrawStatus() == 1) {
				if (loadDialog != null) {
					loadDialog.cancel();
					loadDialog = null;
				}
				loadDialog = DialogUtils.toLoadDialog(this, "提现中...");
			}

			withDrawing = true;
			KkdHttpMagager
					.getInstance()
					.getWithdrawManager(
							mCouponId,
							String.valueOf(df
									.format((mUserWant - mWithDrawFee + mAmount) > 0 ? (mUserWant
											- mWithDrawFee + mAmount)
											: 0)), mPswEt.getText().toString(),
							WithDrawRes.class, new HttpCallBack() {

								@Override
								public void onSuccess(int statusCode, Object res) {
									mWithDrawRes = (WithDrawRes) res;
									mHandler.sendEmptyMessage(WITHDRAW_SUCCESS);

								}

								@Override
								public void onFailure(int statusCode,
										String responseBody) {
									WithdrawActivity.this.statusCode = statusCode;
									Message msg = new Message();
									msg.what = WITHDRAW_FAIL;
									msg.obj = responseBody;
									mHandler.sendMessage(msg);
								}
							});
		}

	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		User user = CurUserModel.getCurUser();
		if (user == null)
			return;
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "加载中...");
		KkdHttpMagager.getInstance().getAccountInfoManager(
				AccountInfoRes.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object res) {

						mAccountInfo = (AccountInfoRes) res;
						withdrawTips = mAccountInfo.getWithdrawTips();
						newMisTips = mAccountInfo.getNewMisTips()
								.getNewMisTips();
						timeSpace = mAccountInfo.getNewMisTips().getTimeSpace();
						mMyBalance = mAccountInfo.getBalance();// data.getDouble("balance");
						bmouts = df.format(mMyBalance);
						mWithDrawFee = Double.parseDouble(mAccountInfo
								.getWithdrawFee());
						if (mMyBalance < mWithDrawFee) {
							bmout = df.format(0);
						} else {
							bmout = df.format(mMyBalance - mWithDrawFee);
						}
						mBankCard = mAccountInfo.getCard();// .getJSONObject("card");
						if (isRequestCouponList) {
							couponList();
							isRequestCouponList = false;
						}
						if (TextUtils.isEmpty(mBankCard.getCardNo())) {

							mHandler.sendEmptyMessage(NO_BANK_CARD);
						} else {
							cardNo = mBankCard.getCardNo();
							bankName = mBankCard.getBankName();
							String limit = mBankCard.getLimit();
							if (limit != null) {
								String[] rechargeAndwithdarw = limit.split("@");
								String withdarw = rechargeAndwithdarw[1];
								everymax = withdarw.split("/");
							} else {
								everymax = new String[2];
								everymax[0] = "5000";
								everymax[1] = "10000";
							}

							mSingleMax = Double.parseDouble(everymax[0]);
							imageUrl = mBankCard.getImageUrl();
							mHandler.sendEmptyMessage(GOT_ACCOUNT_INFO);
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						WithdrawActivity.this.statusCode = statusCode;
						Message msg = new Message();
						msg.what = FAIL_TOAST;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	public void showDialog(String message, final boolean isFinish) {

		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.subscribeDialog(WithdrawActivity.this, message,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						mDialog.dismiss();
						if (isFinish) {
							finish();
						}
					}
				});
		mDialog.show();
		if (isFinish) {
			mDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					finish();

				}
			});
		}

	}

	/**
	 * 选中优惠券
	 */
	public void getSelecterDiscount() {
		double nBmout = getBmoutFormat();// 当前可提余额最大值 ,保证不为负
		bmout = df.format(nBmout);
		if (mId == MyDiscountCouponAdapter.NOT_UESE) {// 不适用优惠券

			mAmountTv.setText("未使用");
			mCouponTv.setText(mDataList.size() + "张优惠券可用");
			mCouponId = "";

		} else { // 使用优惠券

			if ((mCurCoupon.getAmount() * 0.01) > mWithDrawFee) {
				mAmountTv.setText("优惠券不可用");
			} else {
				mAmountTv.setText("¥" + df.format(mAmount));
			}

			mCouponTv.setText(Title);
		}
		withdrawMoneyLogic();

	}

	/**
	 * 优惠券
	 */
	public void couponList() {

		KkdHttpMagager.getInstance().getMyDiscountManager("", "", "2", "true",
				1, 100, 0, MyDiscountCouponData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object res) {

						MyDiscountCouponData mMyDiscountCouponData = (MyDiscountCouponData) res;
						mDataList = mMyDiscountCouponData.getDataList();
						mHandler.sendEmptyMessage(GOT_COUPON);

					}

					@Override
					public void onFailure(int statusCode, String responseBody) {
						WithdrawActivity.this.statusCode = statusCode;
						Message msg = new Message();
						msg.what = FAIL_TOAST;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}
				});
	}

	private void updateWithdrawBtn() {
		boolean enable = false;
		double limit = (mMyBalance > mSingleMax ? mSingleMax : mMyBalance);
		df.format(limit);
		if ((mUserWant - mWithDrawFee + mAmount) > 0 && mUserWant <= limit) {
			// if (mUserWant > 0 && !"".equals(mPswEt.getText().toString())) {
			enable = true;
		}
		next_bt.setEnabled(enable);
	}

	private boolean isUserWantMax() {
		boolean ret = false;
		double nBmout = (mMyBalance - mWithDrawFee + mAmount) > 0 ? (mMyBalance
				- mWithDrawFee + mAmount) : 0;// 当前可提余额最大值 ,保证不为负
		ret = mUserWant >= (nBmout > mSingleMax ? mSingleMax : nBmout);
		return ret;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (pop_line.getVisibility() == View.VISIBLE) {
			closePopwin();
		} else {
			super.onBackPressed();
		}

	}

	protected void showSinaDialog() {
		if (mSinaDialog != null) {
			mSinaDialog.cancel();
			mSinaDialog = null;
		}
		try {
			String text = "";

			if (mAccountInfo.getWithholdAuth().getIsSinaPayPassword() == 0) {
				text = mAccountInfo.getWithholdAuth().getPayPasswordTips();
			} else if (mAccountInfo.getWithholdAuth().getIsWithholdAuth() == 0) {
				text = mAccountInfo.getWithholdAuth().getWithholdAuthTips();
			}
			if (!TextUtils.isEmpty(text)) {
				mSinaDialog = DialogUtils.generate2BDialog(this, text, "去设置",
						"再看看", new OnClickListener() {

							@Override
							public void onClick(View v) {
								mSinaDialog.dismiss();
								Intent intent = new Intent(
										WithdrawActivity.this,
										KKDSinaWebActivity.class);
								intent.putExtra("url", mAccountInfo
										.getWithholdAuth()
										.getSinaWithholdAuthUrl());
								intent.putExtra("useTitleName", true);
								intent.putExtra("titleName", "新浪支付");
								startActivityForResult(intent,
										KKDSinaWebActivity.SET_PWD);
							}
						}, new OnClickListener() {

							@Override
							public void onClick(View v) {
								mSinaDialog.dismiss();
								finish();
							}
						});
				mSinaDialog.show();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * 
	 * 判断是否设置交易密码
	 */
	public void requestIsSetPayPassword() {
		KkdHttpMagager.getInstance().getWithdrawUpdateManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							LogUtil.i("测试", "1");
							int isPayPassword = data.getInt("isPayPassword");
							if (isPayPassword == 1) {
								PreferenceUtils.getInstance()
										.setWithdrawPassWord(
												WithdrawActivity.this, 1);
							} else {
								PreferenceUtils.getInstance()
										.setWithdrawPassWord(
												WithdrawActivity.this, 0);
								showDialog();
							}
						} catch (JSONException e) {

							e.printStackTrace();
						}
						AppUtil.stopProgressDialog();
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						AppUtil.stopProgressDialog();
						showToast(desc);
					}
				});
	}

	public void showDialog() {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.deleteBankDialog(WithdrawActivity.this,
				"您尚未设置提现密码，请先去设置提现密码", new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.confirm_deletebank:
							Intent intent = new Intent(WithdrawActivity.this,
									SetDealActivity.class);
							intent.putExtra("setFlag", 0);
							startActivity(intent);
							if (mDialog != null) {
								mDialog.dismiss();
							}
							break;
						case R.id.cancel_deletebank:
							if (mDialog != null) {
								mDialog.dismiss();
							}
							break;
						}
					}
				});
		mDialog.setCancelable(false);
		mDialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 60 && resultCode == 800) {
			mAmount = 0;
			mId = MyDiscountCouponAdapter.NOT_UESE;
			getSelecterDiscount();
		} else if (requestCode == 60 && resultCode == 900) {
			mCurCoupon = (MyDiscountCouponDataList) data
					.getSerializableExtra(WithdrawDiscountCounponActivity.SER_KEY);
			mId = data.getIntExtra("mId", MyDiscountCouponAdapter.NOT_UESE);
			Title = mCurCoupon.getTitle();
			mAmount = (mCurCoupon.getAmount() * 0.01) > mWithDrawFee ? mWithDrawFee
					: mCurCoupon.getAmount() * 0.01;
			mCouponId = mCurCoupon.getCouponId();
			getSelecterDiscount();
		} else if (requestCode == KKDSinaWebActivity.SET_PWD) {
			if (resultCode == KKDSinaWebActivity.SET_PWD_SUCCESS) {

			} else {
				showSinaDialog();
			}
		}

	}
}
